package com.yonyou.brigade.third_parties.fanscar.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yonyou.brigade.basic_init.enums.ChannelEnum;
import com.yonyou.brigade.order_center.service.IBriOrderService;
import com.yonyou.brigade.third_parties.fanscar.constants.FanscarConstants;
import com.yonyou.brigade.third_parties.fanscar.model.FanscarConfig;
import com.yonyou.brigade.third_parties.fanscar.service.IFanscarOrderService;
import com.yonyou.brigade.third_parties.fanscar.service.IFanscarPublicService;
import com.yonyou.brigade.util.HttpClientUtil;
import com.yonyou.brigade.util.operateutil.DateUtils;
import com.yonyou.brigade.util.operateutil.MD5Util;
import com.yonyou.brigade.ybz.service.IConvertService;
import com.yonyou.ybzboot.starter.mongodb.dao.IMongoDao;
import com.yonyou.ybzboot.starter.mongodb.model.CriteriaMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class FanscarOrderServiceImpl implements IFanscarOrderService {

    @Value("${fanscar.apiUrl}")
    private String apiUrl;

    @Value("${fanscar.tradeFlightType}")
    private String fanscarTradeFlightType;

    @Value("${fanscar.tradeHotelType}")
    private String fanscarTradeHotelType;

    @Value("${fanscar.tradeTrainType}")
    private String fanscarTradeTrainType;

    @Value("${cnv.baigade.system.code}")
    private String systemCode;

    @Value("${cnv.register.userId}")
    private String cnvRegisterUserId;

    @Value("${cnv.register.tenant}")
    private String cnvRegisterTenant;

    @Value("${cnv.register.cookie}")
    private String cnvRegisterCookie;

    @Autowired
    private IFanscarPublicService fanscarPublicService;

    @Autowired
    @Qualifier("briOrderServiceImpl")
    private IBriOrderService briOrderService;

    @Autowired
    @Qualifier("convertServiceImpl")
    private IConvertService convertService;

    @Autowired
    private IMongoDao mongoDao;

    private static final Logger logger = LoggerFactory.getLogger(FanscarPublicServiceImpl.class);


    @Override
    public void getFanscarFlightOrders(FanscarConfig fanscarConfig, String tenant, Date begin, Date end, Integer channelId) {
        HashMap<String, Object> paramMap = new HashMap<>();
        int PageIndex = 1;
        int PageSize = 20;
        Boolean flag = true;
        paramMap.put("OperationStartTime", DateUtils.dateToString(begin));
        paramMap.put("OperationEndTime", DateUtils.dateToString(end));
        paramMap.put("PageSize", PageSize);
        while (flag) {
            paramMap.put("PageIndex", PageIndex);
            String token = fanscarPublicService.getToken(fanscarConfig);
            Map<String, String> header = new HashMap<>();
            header.put("Authorization", "bearer " + token);
            String result = HttpClientUtil.post(apiUrl + FanscarConstants.FLIGHT_ORDER_URI, header, null, JSON.toJSONString(paramMap));
            if (!StringUtils.isEmpty(result)) {
                JSONObject resultJson = JSON.parseObject(result);
                if (resultJson.getInteger("resultCode") == 1) {
                    JSONArray ordersJson = resultJson.getJSONArray("data");
                    Collections.reverse(ordersJson);
                    if (ordersJson != null && ordersJson.size() > 0) {
                        for (int i = 0; i < ordersJson.size(); i++) {
                            JSONObject order = ordersJson.getJSONObject(i);
                            dealWithMongo("flight", order.getString("orderNumber"), order.getString("passengerIdentityNumber"), FanscarConstants.FLIGHT_MONGO_ORDER_TABLENAME, order);
                            //将世界标准时间转换为北京时间
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DateUtils.DD_DATETIME_FORMAT);
                            order.put("departureTime", order.getDate("departureTime") == null ? null : DateUtils.strToDateTime(simpleDateFormat.format(order.getDate("departureTime"))));
                            order.put("creationTime", order.getDate("creationTime") == null ? null : DateUtils.strToDateTime(simpleDateFormat.format(order.getDate("creationTime"))));
                            order.put("orderTime", order.getDate("orderTime") == null ? null : DateUtils.strToDateTime(simpleDateFormat.format(order.getDate("orderTime"))));
                            order.put("arrivalTime", order.getDate("arrivalTime") == null ? null : DateUtils.strToDateTime(simpleDateFormat.format(order.getDate("arrivalTime"))));
                            order.put("flightDate", order.getDate("flightDate") == null ? null : DateUtils.strToDateTime(simpleDateFormat.format(order.getDate("flightDate"))));
                            order.put("operationTime", order.getDate("operationTime") == null ? null : DateUtils.strToDateTime(simpleDateFormat.format(order.getDate("operationTime"))));
                            JSONObject res = convertService.convert(fanscarTradeFlightType, systemCode, cnvRegisterUserId, cnvRegisterTenant, cnvRegisterCookie, order);
                            if (res.getBoolean("success")) {
                                JSONArray results = res.getJSONArray("result");
                                if (results != null && results.size() > 0) {
                                    for (int j = 0; j < results.size(); j++) {
                                        JSONObject jsonObject = results.getJSONObject(j);
                                        JSONObject orderCenter = JSON.parseObject(jsonObject.getString("data"));
                                        if (orderCenter != null && orderCenter.size() > 0) {
                                            String passengerSign = "";
                                            if (!StringUtils.isEmpty(order.getString("passengerIdentityNumber"))) {
                                                passengerSign = MD5Util.getMD5_32(order.getString("passengerIdentityNumber")).substring(8, 24);
                                            }
                                            String orderNo = orderCenter.getString("orderNo") + "_" + passengerSign;
                                            String employeeId = orderCenter.getString("userId");

                                            try {
                                                briOrderService.saveFlight(orderCenter, orderNo, tenant, employeeId, ChannelEnum.FANSCAR.getName(), channelId);
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                                logger.error("泛嘉机票存入订单中心时，出现异常：" + e.getMessage());
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (PageSize * PageIndex++ >= resultJson.getInteger("total")) {
                        flag = false;
                    }
                } else {
                    flag = false;
                }
            } else {
                flag = false;
            }
        }
    }

    @Override
    public void getFanscarHotelOrders(FanscarConfig fanscarConfig, String tenant, Date begin, Date end, Integer channelId) {
        HashMap<String, Object> paramMap = new HashMap<>();
        int PageIndex = 1;
        int PageSize = 20;
        Boolean flag = true;
        paramMap.put("OperationStartTime", DateUtils.dateToString(begin));
        paramMap.put("OperationEndTime", DateUtils.dateToString(end));
        paramMap.put("PageSize", PageSize);
        while (flag) {
            paramMap.put("PageIndex", PageIndex);
            String token = fanscarPublicService.getToken(fanscarConfig);
            Map<String, String> header = new HashMap<>();
            header.put("Authorization", "bearer " + token);
            String result = HttpClientUtil.post(apiUrl + FanscarConstants.HOTEL_ORDER_URI, header, null, JSON.toJSONString(paramMap));
            if (!StringUtils.isEmpty(result)) {
                JSONObject resultJson = JSON.parseObject(result);
                if (resultJson.getInteger("resultCode") == 1) {
                    JSONArray ordersJson = resultJson.getJSONArray("data");
                    Collections.reverse(ordersJson);
                    if (ordersJson != null && ordersJson.size() > 0) {
                        for (int i = 0; i < ordersJson.size(); i++) {
                            JSONObject order = ordersJson.getJSONObject(i);
                            dealWithMongo("hotel", order.getString("orderNumber"), order.getString("passengerId"), FanscarConstants.HOTEL_MONGO_ORDER_TABLENAME, order);
                            //将世界标准时间转换为北京时间
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DateUtils.DD_DATETIME_FORMAT);
                            order.put("orderTime", order.getDate("orderTime") == null ? null : DateUtils.strToDateTime(simpleDateFormat.format(order.getDate("orderTime"))));
                            order.put("departureDate", order.getDate("departureDate") == null ? null : DateUtils.strToDateTime(simpleDateFormat.format(order.getDate("departureDate"))));
                            order.put("arrivalDate", order.getDate("arrivalDate") == null ? null : DateUtils.strToDateTime(simpleDateFormat.format(order.getDate("arrivalDate"))));
                            order.put("createTime", order.getDate("createTime") == null ? null : DateUtils.strToDateTime(simpleDateFormat.format(order.getDate("createTime"))));
                            JSONObject res = convertService.convert(fanscarTradeHotelType, systemCode, cnvRegisterUserId, cnvRegisterTenant, cnvRegisterCookie, order);
                            if (res.getBoolean("success")) {
                                JSONArray results = res.getJSONArray("result");
                                if (results != null && results.size() > 0) {
                                    for (int j = 0; j < results.size(); j++) {
                                        JSONObject jsonObject = results.getJSONObject(j);
                                        JSONObject orderCenter = JSON.parseObject(jsonObject.getString("data"));
                                        if (orderCenter != null && orderCenter.size() > 0) {
                                            String orderNo = orderCenter.getString("orderNo");
                                            String employeeId = orderCenter.getString("userId");
                                            try {
                                                briOrderService.saveHotel(orderCenter, orderNo, tenant, employeeId, ChannelEnum.FANSCAR.getName(), channelId);
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                                logger.error("泛嘉酒店存入订单中心时，出现异常：" + e.getMessage());
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (PageSize * PageIndex++ >= resultJson.getInteger("total")) {
                        flag = false;
                    }
                } else {
                    flag = false;
                }
            } else {
                flag = false;
            }
        }
    }

    @Override
    public void getFanscarTrainOrders(FanscarConfig fanscarConfig, String tenant, Date begin, Date end, Integer channelId) {
        HashMap<String, Object> paramMap = new HashMap<>();
        int PageIndex = 1;
        int PageSize = 20;
        Boolean flag = true;
        paramMap.put("OperationStartTime", DateUtils.dateToString(begin));
        paramMap.put("OperationEndTime", DateUtils.dateToString(end));
        paramMap.put("PageSize", PageSize);
        while (flag) {
            paramMap.put("PageIndex", PageIndex);
            String token = fanscarPublicService.getToken(fanscarConfig);
            Map<String, String> header = new HashMap<>();
            header.put("Authorization", "bearer " + token);
            String result = HttpClientUtil.post(apiUrl + FanscarConstants.TRAIN_ORDER_URI, header, null, JSON.toJSONString(paramMap));
            if (!StringUtils.isEmpty(result)) {
                JSONObject resultJson = JSON.parseObject(result);
                if (resultJson.getInteger("resultCode") == 1) {
                    JSONArray ordersJson = resultJson.getJSONArray("data");
                    Collections.reverse(ordersJson);
                    if (ordersJson != null && ordersJson.size() > 0) {
                        for (int i = 0; i < ordersJson.size(); i++) {
                            JSONObject order = ordersJson.getJSONObject(i);
                            dealWithMongo("train", order.getString("orderNumber"), order.getString("passengerIdentityNumber"), FanscarConstants.TRAIN_MONGO_ORDER_TABLENAME, order);
                            //将世界标准时间转换为北京时间
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DateUtils.DD_DATETIME_FORMAT);
                            order.put("departureTime", order.getDate("departureTime") == null ? null : DateUtils.strToDateTime(simpleDateFormat.format(order.getDate("departureTime"))));
                            order.put("creationTime", order.getDate("creationTime") == null ? null : DateUtils.strToDateTime(simpleDateFormat.format(order.getDate("creationTime"))));
                            order.put("orderTime", order.getDate("orderTime") == null ? null : DateUtils.strToDateTime(simpleDateFormat.format(order.getDate("orderTime"))));
                            order.put("arrivalTime", order.getDate("arrivalTime") == null ? null : DateUtils.strToDateTime(simpleDateFormat.format(order.getDate("arrivalTime"))));
                            order.put("operationTime", order.getDate("operationTime") == null ? null : DateUtils.strToDateTime(simpleDateFormat.format(order.getDate("operationTime"))));
                            order.put("travelDate", order.getDate("travelDate") == null ? null : DateUtils.strToDateTime(simpleDateFormat.format(order.getDate("travelDate"))));

                            JSONObject res = convertService.convert(fanscarTradeTrainType, systemCode, cnvRegisterUserId, cnvRegisterTenant, cnvRegisterCookie, order);
                            if (res.getBoolean("success")) {
                                JSONArray results = res.getJSONArray("result");
                                if (results != null && results.size() > 0) {
                                    for (int j = 0; j < results.size(); j++) {
                                        JSONObject jsonObject = results.getJSONObject(j);
                                        JSONObject orderCenter = JSON.parseObject(jsonObject.getString("data"));
                                        if (orderCenter != null && orderCenter.size() > 0) {
                                            String passengerSign = "";
                                            if (!StringUtils.isEmpty(order.getString("passengerIdentityNumber"))) {
                                                passengerSign = MD5Util.getMD5_32(order.getString("passengerIdentityNumber")).substring(8, 24);
                                            }
                                            String orderNo = orderCenter.getString("orderNo") + "_" + passengerSign;
                                            String employeeId = orderCenter.getString("userId");
                                            try {
                                                briOrderService.saveTrain(orderCenter, orderNo, tenant, employeeId, ChannelEnum.FANSCAR.getName(), channelId);
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                                logger.error("泛嘉火车票存入订单中心时，出现异常：" + e.getMessage());
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (PageSize * PageIndex++ >= resultJson.getInteger("total")) {
                        flag = false;
                    }
                } else {
                    flag = false;
                }
            } else {
                flag = false;
            }
        }
    }

    private void dealWithMongo(String type, String orderId, String passengerIdentityNumber, String mongoName, JSONObject orderJson) {
        CriteriaMap criteriaMap = new CriteriaMap();
        criteriaMap.put("orderNumber", orderId);
        criteriaMap.put("reportType", orderJson.getString("reportType"));
        if ("train".equals(type) || "flight".equals(type)) {
            criteriaMap.put("passengerIdentityNumber", passengerIdentityNumber);
        }
        List<JSONObject> ordersources = mongoDao.findByMap(criteriaMap, JSONObject.class, mongoName);
        if(ordersources != null && ordersources.size() > 0) {
            mongoDao.deleteByMap(criteriaMap, mongoName);
            mongoDao.getMongoTemplate().save(orderJson, mongoName);
        }
        else {
            mongoDao.getMongoTemplate().insert(orderJson, mongoName);
        }
    }
}
